package org.bycloud.security.service;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.bycloud.api.auth.UserService;
import org.bycloud.common.Pager;
import org.bycloud.common.model.User;
import org.bycloud.common.util.EncryptUtils;
import org.bycloud.security.respository.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.extern.slf4j.Slf4j;

@Service("userService")
@Slf4j
public class UserServiceImpl implements UserService {

	@Autowired
	UserDao userDao;

	@Override
	public User findByUsername(String username) {
		return userDao.findByUsername(username);
	}

	@Override
	public Pager<User> findPager(int start, int limit, Object... args) {
		return userDao.findPager(start, limit, args);
	}

	@Override
	public Set<String> findPermissions(String username) {
		Set<String> pers = userDao.findPermissions(username);
		if (log.isDebugEnabled())
			log.debug("username has permission {} ", pers);
		Set<String> newPers = new HashSet<>();
		for (String per : pers) {
			if (!StringUtils.contains(per, ":")) {
				per += ":view";
			}
			newPers.add(per);
		}
		if (log.isDebugEnabled())
			log.debug("username has newPermission {} ", pers);
		return newPers;
	}

	@Override
	public Set<String> findRoleIds(String userId) {
		return userDao.findRoleIds(userId);
	}

	@Override
	public Set<String> findRoles(String username) {
		return userDao.findRoles(username);
	}

	@Override
	@Transactional
	public boolean save(User user) {
		return userDao.mergeUser(user);
	}

	@Override
	@Transactional
	public boolean updatePassword(User user) {
		return userDao.updatePwd(user.getId(),
				EncryptUtils.entryptPassword(user.getPassword(), EncryptUtils.generateSalt()));
	}

}
